<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      table {
        width: 400px;
        border: 1px solid #000;
        border-collapse: collapse;
        margin: 0 auto;
      }

      td,
      th {
        border: 1px solid #000;
        text-align: center;
      }

      input {
        width: 50px;
      }

      .search {
        width: 600px;
        margin: 20px auto;
      }
    </style>
  </head>

  <body>
    <div class="search">
      按照价格查询: <input type="text" class="start" /> -
      <input type="text" class="end" />
      <button class="search-price">搜索</button> 按照商品名称查询:
      <input type="text" class="product" />
      <button class="search-pro">查询</button>
    </div>
    <table>
      <thead>
        <tr>
          <th>id</th>
          <th>产品名称</th>
          <th>价格</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script>
      // 利用新增数组方法操作数据
      var data = [
        {
          id: 1,
          pname: "小米",
          price: 3999,
        },
        {
          id: 2,
          pname: "oppo",
          price: 999,
        },
        {
          id: 3,
          pname: "荣耀",
          price: 1299,
        },
        {
          id: 4,
          pname: "华为",
          price: 1999,
        },
      ];
      // 获取元素
      var tbody = document.querySelector("tbody");
      var search_price = document.querySelector(".search-price");
      var start = document.querySelector(".start");
      var end = document.querySelector(".end");
      var product = document.querySelector(".product");
      var search_pro = document.querySelector(".search-pro");
      // 打开页面先展示数据
      setData(data);
      // 渲染页面
      function setData(obj) {
        // 清空tbody的内容
        tbody.innerHTML = "";
        obj.forEach(function (val) {
          // 创建tr
          var tr = document.createElement("tr");
          // tr里面放内容
          tr.innerHTML = `<td>${val.id}</td><td>${val.pname}</td><td>${val.price}</td>`;
          // 将创建的tr追加到tbody里面
          tbody.appendChild(tr);
        });
      }

      // 按照区间范围来查找数据 用fliter循环查询
      search_price.addEventListener("click", function () {
        var newData = data.filter(function (val) {
          return val.price >= start.value && val.price <= end.value;
        });
        // 重新渲染页面
        setData(newData);
      });
      // 按照精确查询来寻找数据 用some循环来查询
      search_pro.addEventListener("click", function () {
        var arr = [];
        data.some(function (val) {
          if (product.value === val.pname)
            // 将这个数据放入一个新数组中 并终止循环
            arr.push(val);
          return true;
        });
        setData(arr);
      });
    </script>
  </body>
</html>
